package cn.itsource.ymcc.consumer;

import cn.itsource.ymcc.constant.Cons;
import cn.itsource.ymcc.domain.MessageEmail;
import cn.itsource.ymcc.dto.MessageDto;
import cn.itsource.ymcc.service.IMessageEmailService;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.common.message.MessageExt;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.UnsupportedEncodingException;

@Component
@Slf4j
@RocketMQMessageListener(
        consumerGroup = "EmailMessageConsumer",
        topic = Cons.Message.TOPIC_MESSAGE,
        selectorExpression = Cons.Message.TAGS_MESSAGE_EMAIL
)
public class EmailMessageConsumer implements RocketMQListener<MessageExt> {

    @Autowired
    private IMessageEmailService messageEmailService;

    @Override
    public void onMessage(MessageExt message) {
        try {
            byte[] body = message.getBody();
            String jsonStr = new String(body, "utf-8");
            MessageDto messageDto = JSON.parseObject(jsonStr, MessageDto.class);
            log.info("公共服务中接收到邮件发送任务消息......");

            messageDto.getEmailDtoList().forEach(emailDto -> {
                log.info("正在发送邮件给：" + emailDto.getEmail());
                log.info("邮件内容是：" + messageDto.getContent());
                //保存一个邮件发送记录
                MessageEmail messageEmail = new MessageEmail();
                BeanUtils.copyProperties(messageDto, messageEmail);
                BeanUtils.copyProperties(emailDto, messageEmail);
                messageEmailService.save(messageEmail);
            });
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

    }
}
